package com.jhj.service.bm.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jhj.po.bm.mapper.OrderContractMapper;
import com.jhj.po.bm.model.BmOrder;
import com.jhj.po.bm.model.Imgs;
import com.jhj.po.bm.model.OrderContract;
import com.jhj.po.bm.model.Sale;
import com.jhj.po.resume.model.ResumeResource;
import com.jhj.vo.bm.ChartSearchVo;
import com.jhj.vo.bm.OrderContractSearchVo;
import com.jhj.vo.bm.OrderContractVo;
import com.jhj.vo.bm.OrderSearchVo;
import com.jhj.vo.bm.SaleRankVo;
import com.jhj.vo.bm.SaleVo;
import com.jhj.service.bm.BmOrderService;
import com.jhj.service.bm.ImgService;
import com.jhj.service.bm.OrderContractService;
import com.jhj.service.bm.SaleService;
import com.jhj.service.impl.BaseServiceImpl;
import com.jhj.service.resume.ResumeResourceService;
import com.jhj.utils.BeanUtilsExp;
import com.jhj.utils.BmUtil;
import com.jhj.utils.Constants;
import com.jhj.utils.DateUtil;
import com.jhj.utils.MathDoubleUtil;
import com.jhj.utils.StringUtil;
import com.jhj.utils.TimeStampUtil;

@Service
public class OrderContractServiceImpl extends BaseServiceImpl<OrderContract> implements OrderContractService {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	protected OrderContractMapper orderContractMapper;

	@Autowired
	private SaleService saleService;

	@Autowired
	private ImgService imgService;
	
	@Autowired
	private BmOrderService orderService;
	
	@Autowired
	ResumeResourceService resumeResourceService;
	
	@Override
	public OrderContractVo getVo(OrderContract item, BmOrder order) {
		OrderContractVo vo = new OrderContractVo();
		BeanUtilsExp.copyPropertiesIgnoreNull(item, vo);
		Integer orderId = vo.getOrderId();
		Integer userId = order.getUserId();
		String userName = order.getUserName();
		String userMobile = order.getMobile();
		vo.setUserId(userId);
		vo.setUserName(userName);
		vo.setUserMobile(userMobile);

		String saleName = "";
		String saleMobile = "";
		Integer saleId = item.getSaleId();
		if (saleId != null && saleId > 0) {
			Sale sale = saleService.selectByPrimaryKey(saleId);
			saleName = sale.getName();
			saleMobile = sale.getMobile();
		}
		vo.setSaleName(saleName);
		vo.setSaleMobile(saleMobile);

		Integer resumeId = vo.getResumeId();
		String resumeMobile = vo.getResumeMobile();
		String resumeName = vo.getResumeName();

		if (resumeId > 0) {
			
			String headImg = Constants.DEFAULT_HEAD_IMG;
			ResumeResource resSearchVo = new ResumeResource();
			resSearchVo.setResumeId(resumeId);
			resSearchVo.setResourceType(Constants.RES_RESUME_HEAD_IMG);
			List<ResumeResource> resHeadImgList = resumeResourceService.selectBySearchVo(resSearchVo, "add_time desc");
			if (resHeadImgList != null && resHeadImgList.size()>0) {
				headImg = resHeadImgList.get(0).getResourceUrl();
			}
			

			vo.setHeadImg(headImg);
		}

		vo.setResumeId(resumeId);
		vo.setResumeMobile(resumeMobile);
		vo.setResumeName(resumeName);

		// 合同图片资源
		Imgs searchVo = new Imgs();
		searchVo.setOrderId(orderId);
		searchVo.setLinkId(vo.getId());
		searchVo.setImgType(Constants.IMG_TYPE_ORDER_CONTRACT);
		List<Imgs> imgs = imgService.selectBySearchVo(searchVo, "img_id desc");
		if (imgs == null)
			imgs = new ArrayList<Imgs>();
		vo.setContractImgs(imgs);

		String contractDay = DateUtil.getToday();
		if (vo.getConcatTime() > 0) {
			Long t = Long.valueOf(vo.getConcatTime()) * 1000;
			contractDay = TimeStampUtil.timeStampToDateStr(t, DateUtil.DEFAULT_PATTERN);
		}
		vo.setContractDay(contractDay);
		
		//获取服务开始时间和结束时间
		String contractStartDate = this.getContractStartDate(item);
		vo.setContractStartDate(contractStartDate);
		
		String contractEndDate = this.getContractEnd(item);
		vo.setContractEndDate(contractEndDate);
		
		//服务类型
		vo.setServiceTypeId(order.getServiceTypeId());
		vo.setServiceTypeName(order.getServiceTypeName());
		
		//合同状态名称
		String statusName = "";
		statusName = BmUtil.getContractStatus(vo.getStatus());
		vo.setStatusName(statusName);
		
		return vo;
	}

	@Override
	public List<Map<String, String>> countSaleOrderMoney(ChartSearchVo vo) {

		return orderContractMapper.countSaleOrderMoney(vo);
	}

	@Override
	public List<Map<String, String>> countSaleOrderNum(ChartSearchVo vo) {

		return orderContractMapper.countSaleOrderMoney(vo);
	}

	@Override
	public List<Map<Integer, BigDecimal>> sumSaleOrderPay(ChartSearchVo searchVo) {
		return orderContractMapper.sumSaleOrderPay(searchVo);
	}
	
	/**
	 * 统计销售老师各个指标，签约数，总金额，总服务费用，总渠道费用.
	 */
	
	@Override
	public List<SaleRankVo> saleRankStat(ChartSearchVo searchVo) {
		
		List<SaleRankVo> result = new ArrayList<SaleRankVo>();
		//找出所有的销售老师
		SaleVo saleVo = new SaleVo();

		if (!StringUtil.isEmpty(searchVo.getSaleMobile())) saleVo.setMobile(searchVo.getSaleMobile());
		if (!StringUtil.isEmpty(searchVo.getSaleName())) saleVo.setName(searchVo.getSaleName());
		if (searchVo.getSaleId() != null) saleVo.setSaleId(searchVo.getSaleId());
		
		List<Sale> saleList = saleService.selectBySearchVo(saleVo, "");
		
		
		String startTimeStr = searchVo.getStartTimeStr();
		Integer startTime = searchVo.getStartTime();
		// 开始时间和结束时间
		if (!StringUtil.isEmpty(startTimeStr) && ( startTime == null || startTime.equals(0) ) ) {
			startTime = (int) (TimeStampUtil.getMillisOfDayFull(startTimeStr + " 00:00:00") / 1000);
			searchVo.setStartTime(startTime);
		}

		
		String endTimeStr = searchVo.getEndTimeStr();
		Integer endTime = searchVo.getEndTime();
		// 开始时间和结束时间
		if (!StringUtil.isEmpty(endTimeStr) && ( endTime == null || endTime.equals(0) ) ) {
			endTime = (int) (TimeStampUtil.getMillisOfDayFull(endTimeStr + " 00:00:00") / 1000);
			searchVo.setEndTime(endTime);
		}
		
		List<SaleRankVo> saleRankList = orderContractMapper.saleRankStat(searchVo);
		
		//获取订单总数
		OrderSearchVo orderSearchVo = new OrderSearchVo();
		if (searchVo.getSaleId() != null) orderSearchVo.setSaleId(searchVo.getSaleId());
		if (searchVo.getStartTime() != null) orderSearchVo.setStartTime(searchVo.getStartTime());
		if (searchVo.getEndTime() != null) orderSearchVo.setEndTime(searchVo.getEndTime());
		if (searchVo.getServiceTypeId() != null) orderSearchVo.setServiceTypeId(searchVo.getServiceTypeId());
		if (!StringUtil.isEmpty(searchVo.getSaleMobile())) orderSearchVo.setSaleMobile(searchVo.getSaleMobile());
		if (!StringUtil.isEmpty(searchVo.getSaleName())) orderSearchVo.setSaleName(searchVo.getSaleName());
		List<Map<Integer, Integer>> orderStats = orderService.countOrderSale(orderSearchVo);
		
		
		int saleListlen = saleList.size();
		int saleRankLen = saleRankList.size();
		int orderStatLen = orderStats.size();
		for (int i = 0 ; i < saleListlen ; i++) {
			Sale sale = saleList.get(i);
			Integer saleId = sale.getSaleId();
			SaleRankVo item = BeanUtilsExp.initClass(new SaleRankVo());
			
			for (int k = 0; k < saleRankLen; k++) {
				SaleRankVo tempItem = saleRankList.get(k);
				Integer tmpSaleId = tempItem.getSaleId();
				if (saleId.equals(tmpSaleId)) {
					item = tempItem;
					break;
				}
			}
			
			item.setSaleName(sale.getName());
			item.setSaleMobile(sale.getMobile());
			
			Integer totalOrder = 0;
			Integer totalOrderOngoing = 0;
			for (int j = 0; j < orderStatLen; j++) {
				Map<Integer, Integer> orderStat = orderStats.get(j);
				Integer tmpSaleId = orderStat.get("saleId").intValue();
				if (saleId.equals(tmpSaleId)) {
					Number totalNum = orderStat.get("total");
//					if (!StringUtil.isEmpty(totalStr)) {
						totalOrder = totalNum.intValue();
//					}
					
					Number totalProcess = orderStat.get("totalProcess");
//					
					totalOrderOngoing = totalProcess.intValue();	
						
					break;
				}
			}
			
			item.setTotalOrder(totalOrder);
			item.setTotalOrderOngoing(totalOrderOngoing);
			//签约转化率 = 总签约量 / 总订单数.
			Integer totalOrderDone = item.getTotalOrderDone();
			String orderDoneRadio = MathDoubleUtil.getPercent(totalOrderDone, totalOrder);
			item.setOrderDoneRatio(orderDoneRadio);
			
			result.add(item);
		}
		
		//进行排序后排名
		Collections.sort(result, new Comparator<SaleRankVo>() {
			@Override
			public int compare(SaleRankVo s1, SaleRankVo s2) {
				return s2.getTotalOrderPay().compareTo(s1.getTotalOrderPay());
			}
		});
		
		int len = result.size();
		for (int i = 0 ; i < len ; i++) {
			SaleRankVo item = result.get(i);
			item.setRankNum(i+1);
			result.set(i, item);
		}
		
		return result;
	}
	
	/**
	 * 获取合同开始的时间点
	 */
	@Override
	public String getContractStartDate(OrderContract item) {
		String contractDateStr = "";

		String fromDate = item.getFromDate();

		if (!StringUtil.isEmpty(fromDate))
			return fromDate;

		Long contractTime = Long.valueOf(item.getConcatTime());
		String contractBeginDateStr = TimeStampUtil.timeStampToDateStr(contractTime * 1000, DateUtil.DEFAULT_PATTERN);
//		Date contractBeginDate = DateUtil.parse(contractBeginDateStr);

		return contractBeginDateStr;

	}

	/**
	 * 获取合同结束的时间点
	 */
	@Override
	public String getContractEnd(OrderContract item) {
		String contractDateStr = "";

		String toDate = item.getToDate();

		if (!StringUtil.isEmpty(toDate))
			return toDate;

		Long contractTime = Long.valueOf(item.getConcatTime());
		String contractBeginDateStr = TimeStampUtil.timeStampToDateStr(contractTime * 1000, DateUtil.DEFAULT_PATTERN);
		Date contractBeginDate = DateUtil.parse(contractBeginDateStr);

		Integer contractEnd = item.getContractEnd();

		// 1 = 26天
		if (contractEnd == 1) {
			contractDateStr = DateUtil.addDay(contractBeginDate, 26, Calendar.DATE, DateUtil.DEFAULT_PATTERN);
		}

		// 2 = 42天
		if (contractEnd == 2) {
			contractDateStr = DateUtil.addDay(contractBeginDate, 42, Calendar.DATE, DateUtil.DEFAULT_PATTERN);
		}

		// 3 = 58天
		if (contractEnd == 3) {
			contractDateStr = DateUtil.addDay(contractBeginDate, 58, Calendar.DATE, DateUtil.DEFAULT_PATTERN);
		}

		// 4 = 1个月
		if (contractEnd == 4) {
			contractDateStr = DateUtil.addDay(contractBeginDate, 1, Calendar.MONTH, DateUtil.DEFAULT_PATTERN);
		}

		// 5 = 2个月
		if (contractEnd == 5) {
			contractDateStr = DateUtil.addDay(contractBeginDate, 2, Calendar.MONTH, DateUtil.DEFAULT_PATTERN);
		}

		// 6 = 半年
		if (contractEnd == 6) {
			contractDateStr = DateUtil.addDay(contractBeginDate, 6, Calendar.MONTH, DateUtil.DEFAULT_PATTERN);
		}

		// 7 = 一年
		if (contractEnd == 7) {
			contractDateStr = DateUtil.addDay(contractBeginDate, 1, Calendar.YEAR, DateUtil.DEFAULT_PATTERN);
		}

		return contractDateStr;

	}

	/**
	 * 获取合同所有日期列表
	 */
	@Override
	public List<String> getContractDates(OrderContract item) {
		List<String> datas = new ArrayList<String>();
		String beginDateStr = "";
		String endDateStr = "";

		String fromDateStr = item.getFromDate();
		String toDateStr = item.getToDate();

		if (!StringUtil.isEmpty(fromDateStr) && !StringUtil.isEmpty(toDateStr)) {
			beginDateStr = fromDateStr;
			endDateStr = toDateStr;
		} else {
			Long contractTime = Long.valueOf(item.getConcatTime());
			beginDateStr = TimeStampUtil.timeStampToDateStr(contractTime * 1000, DateUtil.DEFAULT_PATTERN);
			endDateStr = this.getContractEnd(item);
		}

		if (StringUtil.isEmpty(beginDateStr) || StringUtil.isEmpty(endDateStr)) {
			return datas;
		}

		Date beginDate = DateUtil.parse(beginDateStr);

		int i = 0;
		while (true) {
			String curDateStr = DateUtil.addDay(beginDate, i, Calendar.DATE, DateUtil.DEFAULT_PATTERN);
			if (DateUtil.compare(endDateStr, curDateStr) == true)
				break;
			datas.add(curDateStr);
			i++;
		}
		return datas;

	}

	@Override
	public String getContractNo() {
		return DateUtil.getNow("yyyyMMddHHmmss");
	}

	@SuppressWarnings({ "rawtypes" })
	@Override
	public PageInfo selectByListPage(OrderContractSearchVo searchVo, int pageNo, int pageSize, String orderBy) {
		PageHelper.startPage(pageNo, pageSize);
		
		if (!StringUtil.isEmpty(orderBy)) searchVo.setOrderBy(orderBy);
		
		List<OrderContract> list = orderContractMapper.selectByListPage(searchVo);
		PageInfo<OrderContract> pageInfo = new PageInfo<OrderContract>(list);
		return pageInfo;
	}
	
	@Override
	public Integer statNumBySearchVo(ChartSearchVo searchVo) {
		Integer result = 0;
		
		result = orderContractMapper.statNum(searchVo);
		if (result == null) result = 0;
		
		return result;
	}
}
